<?php

	require_once __CFG_PATH_LIBS_ADMIN.__CFG_PATH_CORE_CLASSES."class.FTPAgent.php";
	require_once __CFG_PATH_LIBS_ADMIN.__CFG_PATH_CORE_CLASSES."class.MainFunc.php";

	MainFunc::setParams();

	class FTPFile extends FTPAgent
	{		
		public function uploadFile($tmpFileArr, $Destination)
		{
			$args = func_get_args();
			$maxFileSize = intval($args[2]);
			if(!MainFunc::isBlank($tmpFileArr['tmp_name']))
			{
				$LocalFile = $tmpFileArr['tmp_name'];
				$this->makeDir(dirname($Destination));
				if($tmpFileArr['error'] == 0)
				{
					if(!$maxFileSize)
					{
						$maxFileSize = MainFunc::$Config['imFileMaxSize'];
					}
					if($tmpFileArr['size'] <= $maxFileSize)
					{
						$result = parent::uploadFile($Destination, $LocalFile);		
						if(!$result)
						{
							$this->addErrorMessage(MainFunc::$ERRORS['admin'][__ERROR_WRONG_UPLOAD_FILE]." ".$Destination);
							return false;
						}
					}
					else
					{
						$this->addErrorMessage(MainFunc::$ERRORS['admin'][__ERROR_WRONG_FILE_SIZE]);
						return false;
					}
				}
				else
				{
					$this->addErrorMessage(MainFunc::$ERRORS['admin'][__ERROR_SOME_ERRORS_WITH_FILE]);
					return false;
				}
			}
		
			return $Destination;
		}
		
		public function uploadFileHandler($FieldName, $FieldArray, $FilesArr)
		{
			if(isset($FilesArr[$FieldName]) && is_array($FilesArr[$FieldName]) && $FilesArr[$FieldName]['size'] > 0)
			{
				$fileType = $this->getFileType($FilesArr[$FieldName]['name']);
				if(!is_array($FieldArray['filetype']))
				{
					$fileTypes = explode(',', $FieldArray['filetype']);
				}
				else
				{
					$fileTypes = $FieldArray['filetype'];
				}
					
				if(!in_array($fileType, $fileTypes))
				{
					$this->addErrorMessage(MainFunc::$ERRORS['admin'][__ERROR_SOME_ERRORS_WITH_FILE]);
					return false;
				}
					
				if($FieldArray['currentValue'])
				{
					$this->deleteFile($FieldArray['currentValue']);
				}
					
				do
				{
					$fileName = $FieldArray['filenamePrefix'].MainFunc::generate_password($FieldArray['filenameLength'], $FieldArray['filenameSymbols']).$fileType;
				}
				while($this->isFilePresent($FieldArray['dirname'], $fileName));
				
				$maxFileSize = (isset($FieldArray['fileSize'])) ? intval($FieldArray['fileSize']) : null;
					
				return $this->uploadFile($FilesArr[$FieldName], $FieldArray['dirname'].$fileName, $maxFileSize);
			}
		}
		
		public function editItemFieldHandler($FieldName, $FieldArray, $FilesArr)
		{
			return $this->uploadFileHandler($FieldName, $FieldArray, $FilesArr);
		}
		
		public function addFieldHandler($FieldName, $FieldArray, $FilesArr)
		{
			return $this->uploadFileHandler($FieldName, $FieldArray, $FilesArr);
		}
		
	}


?>